<template>
  <article>
    <!--banner begin-->
    <div class="picsbox">
      <FirstRecommend></FirstRecommend>
      <!--banner end-->

      <!-- 二级推荐 -->
      <div class="toppic">
        <li v-for="item in secondData" :key="item.uid" @click="goToInfo(item)" :style="{ borderRadius: '15px' }">
          <a href="javascript:void(0);">
            <i>
              <img v-if="item.photoList" :src="item.photoList[0]">
            </i>
            <h2>{{item.title}}</h2>
            <span>{{item.blogSort.sortName}}</span>
          </a>
        </li>
      </div>
    </div>

    <div class="blank"></div>

    <!--blogsbox begin-->
    <div class="blogsbox">


      <div class="topclassify" v-if="allButtons.length > 1">
        <div class="button-list">
          <!-- 显示前5个按钮 -->
          <button class="button" v-for="(item, index) in visibleButtons" :key="item.uid"
            @click="clickClassify(item.uid)">
            {{ item.sortName }}
          </button>
          <!-- 显示更多按钮 -->
          <button class="button more-btn" @click="toggleMore">{{ showMore ? '收起' : '更多' }}</button>
        </div>
        <!-- 更多按钮显示的容器，使用 transition 组件添加滑动效果 -->
        <transition name="slide-fade">
          <div class="more-container" v-if="showMore">
            <button class="button" v-for="(item, index) in moreButtons" :key="item.uid"
              @click="clickClassify(item.uid)">
              {{ item.sortName }}
            </button>
          </div>
        </transition>
      </div>

      <div class="blogs" style="padding-bottom: 30px; justify-content: center;" v-show="isLogin">
        <el-button type="primary" @click="openDialog" class="custom-button">
          发布博客
        </el-button>
      </div>

      <div v-for="item in newBlogData" :key="item.uid" class="blogs" data-scroll-reveal="enter bottom over 1s">
        <div style="display: flex;">
          <div class="author">
            <span class="iconfont">&#xe60f;</span>
            <span>{{item.author}}</span>
          </div>
          <div class="createTime">
            <span class="iconfont">&#xe606;</span>
            {{item.createTime}}
          </div>
        </div>

        <h3 class="blogtitle">
          <a href="javascript:void(0);" @click="goToInfo(item)">{{item.title}}</a>
        </h3>

        <p class="blogtext">{{item.summary}}</p>

        <span class="blogpic">
          <img v-for="(photo, index) in item.photoList" :key="index" :src="photo" alt="" />
        </span>


        <div class="bloginfo">
          <ul>
            <li class="lmname" v-if="item.blogSort">
              <span class="iconfont">&#xe603;</span>
              <a href="javascript:void(0);">{{item.blogSort.sortName}}</a>
            </li>
            <li class="view">
              <span class="iconfont">&#xe8c7;</span>
              <span>{{item.clickCount}}</span>
            </li>
            <li class="like">
              <span class="iconfont">&#xe663;</span>
              {{item.collectCount}}
            </li>
          </ul>
        </div>
      </div>



      <div class="isEnd">
        <!-- <span v-if="!isEnd">正在加载中~</span> -->

        <div class="loadContent" @click="loadContent" v-if="!isEnd&&!loading">点击加载更多</div>

        <div class="lds-css ng-scope" v-if="!isEnd&&loading">
          <div style="width:100%;height:100%" class="lds-facebook">
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>

        <span v-if="isEnd">我也是有底线的~</span>
      </div>
    </div>
    <!--blogsbox end-->

    <div class="sidebar">
      <!--标签云-->
      <TagCloud :hotTagData="hotTagData"></TagCloud>
      <!--点击排行-->
      <HotBlog></HotBlog>

    </div>

    <el-dialog title="添加博客" :visible.sync="dialogVisible" :width="dialogWidth">
      <AddBlog :allButtons="allButtons" :hotTagData="hotTagData"></AddBlog>
    </el-dialog>

  </article>
</template>

<script>
  import FirstRecommend from "../components/FirstRecommend";
  import ThirdRecommend from "../components/ThirdRecommend";
  import FourthRecommend from "../components/FourthRecommend";
  import TagCloud from "../components/TagCloud";
  import HotBlog from "../components/HotBlog";
  import AddBlog from "./my/addBlog"
  import {
    getBlogSortList,
    getArticleByBlogSortUid
  } from "../api/classify";
  import {
    getBlogByLevel,
    getNewBlog,
    recorderVisitPage,
    getHotTag
  } from "../api/index";
  import {
    Loading
  } from 'element-ui';
  import {
    getBlogByUid
  } from "../api/blogContent";
  export default {
    name: "index",
    components: {
      //注册组件
      FirstRecommend,
      FourthRecommend,
      ThirdRecommend,
      TagCloud,
      HotBlog,
      AddBlog
    },
    watch: {
      '$store.state.user.isLogin'(newVal, oldVal) {
        // 状态更新时执行的操作
        if (newVal == true) {
          // 用户已登录
          console.log('User is now logged in.');
          this.isLogin = true;
        } else {
          // 用户未登录
          console.log('User is now logged out.');
          this.isLogin = false;
        }
      }
    },
    data() {
      return {
        isLogin: false,
        listQuery: {},
        dialogVisible: false,
        classifyUid: 0,
        showMore: false,
        visibleCount: 5,
        allButtons: [{
            sortName: '全部',
            uid: 0,
          }
          // 你可以继续添加其他按钮
        ],
        stickyOffset: 0, // 根据实际情况设置偏移值
        loadingInstance: null, // loading对象
        VUE_XUAN_WEB: process.env.VUE_XUAN_WEB,
        secondData: [], //；二级级推荐数据
        newBlogData: [], //最新文章
        hotTagData: [], //最新标签
        keyword: "",
        currentPage: 1,
        pageSize: 10,
        total: 0, //总数量
        isEnd: false, //是否到底底部了
        loading: false //是否正在加载
      };
    },
    computed: {
      dialogWidth() {
        // 判断当前屏幕宽度，设置对应的宽度
        if (window.innerWidth <= 768) {
          return '100%'; // 移动端时设置为 100%
        } else {
          return '50%'; // 默认宽度为 50%
        }
      },
      visibleButtons() {
        return this.allButtons.slice(0, this.visibleCount);
      },
      moreButtons() {
        return this.allButtons.slice(this.visibleCount);
      }
    },
    mounted() {
      const sidebar = this.$el.querySelector('.sidebar');
      this.stickyOffset = sidebar.offsetTop; // 获取 .sidebar 元素距离顶部的距离
      window.addEventListener('resize', this.updateFixedPosition);

      // 添加滚动事件监听器
      window.addEventListener('scroll', this.handleScroll);
      this.loading = false;

      // console.log(this.$store.state.user.userInfo);
      // console.log(this.$store.state.user.isLogin)
      // this.isLogin = this.$store.state.user.isLogin;
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.updateFixedPosition);
      // 在组件销毁前移除滚动监听
      window.removeEventListener('scroll', this.handleScroll);
    },
    created() {
      var secondParams = new URLSearchParams();
      secondParams.append("level", 2);
      // 是否排序
      secondParams.append("useSort", 1);
      getBlogByLevel(secondParams).then(response => {
        if (response.code == this.$ECode.SUCCESS) {
          this.secondData = response.data.records;
        }
      });
      // 获取最新博客
      this.newBlogList();
      var params = new URLSearchParams();
      params.append("pageName", "INDEX");
      recorderVisitPage(params).then(response => {});
      this.getClassify();
      getHotTag().then(response => {
        if (response.code === this.$ECode.SUCCESS) {
          this.hotTagData = response.data;
        }
      });
      this.isLogin = this.$store.state.user.isLogin;
    },

    methods: {

      openDialog() {
        this.dialogVisible = true;
      },
      clickClassify(uid) {
        if (uid != null) {
          this.classifyUid = uid;
          if (uid === 0) {
            this.newBlogList();
            return;
          }
        }
        this.currentPage = 1;
        this.newBlogData = [],
          this.getBlogByClassify()
      },
      getBlogByClassify() {
        var that = this;
        that.loadingInstance = Loading.service({
          lock: true,
          text: '正在努力加载中……',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        var params = new URLSearchParams();
        params.append("blogSortUid", this.classifyUid);
        params.append("currentPage", this.currentPage);
        params.append("pageSize", this.pageSize);
        getArticleByBlogSortUid(params).then(response => {
          if (response.code == this.$ECode.SUCCESS) {
            for (let i = 0; i < response.data.records.length; i++) {
              that.newBlogData.push(response.data.records[i]);
            }
            that.total = response.data.total;
            that.pageSize = response.data.size;
            that.currentPage = response.data.current;
            // console.log(response)
          }
          this.isEnd = false;
          if (that.newBlogData.length >= that.total) {
            that.isEnd = true;
          }
          // console.log(this.allButtons)

          that.loadingInstance.close();
        }, function(err) {
          that.loadingInstance.close();
          this.isEnd = true;
        });
      },
      getClassify() {
        var that = this;
        getBlogSortList().then(response => {
          if (response.code == this.$ECode.SUCCESS) {
            var activities = response.data;
            for (var a = 0; a < activities.length; a++) {
              var dataForDate = {
                sortName: activities[a].sortName,
                uid: activities[a].uid
              };
              this.allButtons.push(dataForDate);
            }
          }
        });
        console.log(this.allButtons)
      },
      beforeEnter(el) {
        el.style.transform = 'translateY(-100%)';
        el.style.opacity = 0;
      },
      enter(el, done) {
        el.offsetHeight; // trigger reflow
        el.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
        el.style.transform = 'translateY(0)';
        el.style.opacity = 1;
        done();
      },
      leave(el, done) {
        el.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
        el.style.transform = 'translateY(-100%)';
        el.style.opacity = 0;
        done();
      },
      toggleMore() {
        this.showMore = !this.showMore;
      },
      updateFixedPosition() {
        const fixedElement = this.$el.querySelector('.fixed');
        const blogsBox = this.$el.querySelector('.blogsbox');

        if (fixedElement && blogsBox) {
          const viewportWidth = window.innerWidth;
          const blogsBoxRect = blogsBox.getBoundingClientRect();
          const blogsBoxRight = viewportWidth - blogsBoxRect.right;

          fixedElement.style.right = blogsBoxRight - 417 + 'px';
        }
      },
      handleScroll() {
        // console.log(window.pageYOffset)
        // console.log(sticky)
        const sidebar = this.$el.querySelector('.sidebar');
        if (window.pageYOffset >= this.stickyOffset + 110) {
          sidebar.classList.add('fixed');
          this.updateFixedPosition()
        } else {
          sidebar.classList.remove('fixed');
        }

        const documentHeight = document.documentElement.scrollHeight;
        // 获取当前滚动位置
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        // 获取视口高度
        const windowHeight = window.innerHeight || document.documentElement.clientHeight;
        // 计算距离底部的距离
        const distanceFromBottom = documentHeight - (scrollTop + windowHeight);
        // console.log(distanceFromBottom)
        let value = 203;
        if (distanceFromBottom <= value) {
          sidebar.style.top = distanceFromBottom - value + 'px'
        } else {
          sidebar.style.top = '0px'
        }


      },
      //跳转到文章详情【或推广链接】
      goToInfo(blog) {
        if (blog.type == "0") {
          let routeData = this.$router.resolve({
            path: "/info",
            query: {
              blogOid: blog.oid
            }
          });
          window.open(routeData.href, '_blank');
        } else if (blog.type == "1") {
          var params = new URLSearchParams();
          params.append("uid", blog.uid);
          getBlogByUid(params).then(response => {
            // 记录一下用户点击日志
          });
          window.open(blog.outsideLink, '_blank');
        }
      },
      //跳转到搜索详情页
      goToList(uid) {
        let routeData = this.$router.push({
          path: "/list",
          query: {
            sortUid: uid
          }
        });

      },
      //跳转到搜索详情页
      goToAuthor(author) {
        let routeData = this.$router.push({
          path: "/list",
          query: {
            author: author
          }
        });
      },
      //最新博客列表
      newBlogList() {
        var that = this;
        that.loadingInstance = Loading.service({
          lock: true,
          text: '正在努力加载中……',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        var params = new URLSearchParams();
        params.append("currentPage", this.currentPage);
        params.append("pageSize", this.pageSize);
        getNewBlog(params).then(response => {
          if (response.code == this.$ECode.SUCCESS) {
            that.newBlogData = response.data.records;
            that.total = response.data.total;
            that.pageSize = response.data.size;
            that.currentPage = response.data.current;
          }
          that.loadingInstance.close();
        }, function(err) {
          that.loadingInstance.close();
        });
      },

      loadContent: function() {
        var that = this;
        that.loading = false;
        that.currentPage = that.currentPage + 1;
        if (this.classifyUid == 0) {
          var params = new URLSearchParams();
          params.append("currentPage", that.currentPage);
          params.append("pageSize", that.pageSize);
          getNewBlog(params).then(response => {
            if (response.code == this.$ECode.SUCCESS && response.data.records.length > 0) {
              that.isEnd = false;
              var newData = that.newBlogData.concat(response.data.records);
              that.newBlogData = newData;
              that.total = response.data.total;
              that.pageSize = response.data.size;
              that.currentPage = response.data.current;

              //全部加载完毕
              if (newData.length < that.pageSize) {
                that.isEnd = true;
              }
            } else {
              that.isEnd = true;
            }
            that.loading = false;
          });
        } else {
          this.getBlogByClassify();
        }

      }
    }
  };
</script>

<style scoped>
  .custom-button {
    width: 60%;
    height: 50px;
    border-radius: 8px;
    line-height: 10px;
    text-align: center;
    /* 文字居中对齐 */
  }

  .dialog-footer {
    text-align: right;
  }


  /* 博客信息 */
  .bloginfo {
    position: absolute;
    bottom: 16px;
    left: 16px;
    width: calc(100% - 32px);
    overflow: hidden;
    font-size: 12px;
    margin-top: 0;
    width: 100%;
    clear: both;
  }

  /* 博客信息列表 */
  .bloginfo ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  /* 博客信息列表项 */
  .bloginfo ul li {
    float: left;
    padding: 0 10px;
    color: #748594;
    line-height: 1.5;
    display: inline-block;
  }

  /* 博客信息列表项链接 */
  .bloginfo ul li a {
    color: #748594;
  }

  /* 链接悬停效果 */
  .bloginfo ul li a:hover {
    color: #000;
  }

  .bloginfo ul li {
    background-image: none
  }

  .bloginfo .createTime {
    display: none
  }

  .bloginfo ul li {
    margin-right: 5px
  }

  .topclassify {
    position: relative;
    overflow: hidden;
    border-radius: 8px;
    margin-bottom: 20px;
    padding: 30px 30px 30px 30px;
    background: #FFF;
    -webkit-box-shadow: 0 2px 5px 0 rgba(146, 146, 146, .1);
    -moz-box-shadow: 0 2px 5px 0 rgba(146, 146, 146, .1);
    box-shadow: 0 2px 5px 0 rgba(146, 146, 146, .1);
    /*    -webkit-transition: all 0.6s ease;
     -moz-transition: all 0.6s ease;
     -o-transition: all 0.6s ease; */
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }

  .topclassify:hover {
    transform: translateY(-5px);
    /* 向上浮动 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    /* 添加阴影效果 */
  }

  .button-list {
    display: flex;
    flex-wrap: wrap;
    gap: 36px;
  }

  @media (max-width: 768px) {
    .button-list {
      gap: 5px;
      /* 在小屏幕上减少间距 */
      justify-content: center;
      /* 居中对齐按钮 */
    }

    .button {
      width: 100px;
      /* 固定宽度 */
      height: 50px;
      /* 固定高度 */
    }
  }

  .button {
    padding: 10px 20px;
    border: none;
    background-color: #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s, box-shadow 0.3s;
  }

  .button:hover {
    background-color: #ddd;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  }

  .more-btn {
    background-color: #007bff;
    color: white;
  }

  .more-btn:hover {
    background-color: #0056b3;
  }

  .more-container {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    margin-top: 20px;
    border-top: 1px solid #ccc;
    padding-top: 20px;
    padding-bottom: 10px;
    background-color: #FFF;
  }

  .more-container .button {
    margin-right: 10px;
    white-space: nowrap;
  }

  /* CSS 动画 */
  .slide-fade-enter-active,
  .slide-fade-leave-active {
    transition: opacity 0.3s ease, transform 0.3s ease;
  }

  .slide-fade-enter,
  .slide-fade-leave-to {
    opacity: 0;
    transform: translateY(-100%);
  }


  .el-loading-mask {
    z-index: 2002;
  }

  .isEnd {
    float: left;
    width: 100%;
    height: 80px;
    text-align: center;
  }

  .ng-scope {
    margin: 0 auto;
    width: 18%;
    height: 10%;
  }


  @keyframes lds-facebook_1 {
    0% {
      top: 0px;
      height: 200px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_1 {
    0% {
      top: 0px;
      height: 200px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @keyframes lds-facebook_2 {
    0% {
      top: 20px;
      height: 160px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_2 {
    0% {
      top: 20px;
      height: 160px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @keyframes lds-facebook_3 {
    0% {
      top: 40px;
      height: 120px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_3 {
    0% {
      top: 40px;
      height: 120px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  .lds-facebook {
    position: relative;
  }

  .lds-facebook div {
    position: absolute;
    width: 20px;
  }

  .lds-facebook div:nth-child(1) {
    left: 40px;
    background: #1d0e0b;
    -webkit-animation: lds-facebook_1 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_1 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    -webkit-animation-delay: -0.2s;
    animation-delay: -0.2s;
  }

  .lds-facebook div:nth-child(2) {
    left: 90px;
    background: #774023;
    -webkit-animation: lds-facebook_2 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_2 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    -webkit-animation-delay: -0.1s;
    animation-delay: -0.1s;
  }

  .lds-facebook div:nth-child(3) {
    left: 140px;
    background: #d88c51;
    -webkit-animation: lds-facebook_3 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_3 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
  }

  .lds-facebook {
    width: 90px !important;
    height: 90px !important;
    -webkit-transform: translate(-45px, -45px) scale(0.45) translate(45px, 45px);
    transform: translate(-45px, -45px) scale(0.45) translate(45px, 45px);
  }

  .iconfont {
    font-size: 15px;
    margin-right: 2px;
  }
</style>
